package com.cqc.jdk8.Jutil;

import org.junit.Test;

import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;

/**
 * 合并 list  set map的几种方法
 */
public class ListSetMapMergeTest {

    @Test
    public void listAddAll() {
        List<String> list1 = new ArrayList<>(Arrays.asList("A", "B"));
        List<String> list2 = Arrays.asList("C", "D");
        //会改变原集合
        list1.addAll(list2);
        System.out.println(list1);
    }

    @Test
    public void listConcat() {
        List<String> list1 = Arrays.asList("A", "B");
        List<String> list2 = Arrays.asList("C", "D");
        //不会改变原集合，而是会生成新集合
        List<String> list = Stream.concat(list1.stream(), list2.stream())
                .collect(Collectors.toList());
        System.out.println(list);
    }


    @Test
    public void f1() {
        List<String> list1 = Arrays.asList("A", "B");
        List<String> list2 = Arrays.asList("C", "D");
        List<String> list3 = Stream.of(list1, list2)
                .flatMap(list -> list.stream())
                .collect(Collectors.toList());
        System.out.println(list3);
    }

    @Test
    public void mapPutAll() {
        Map<String, Integer> map1 = new HashMap<>();
        map1.put("A", 1);
        map1.put("B", 2);
        Map<String, Integer> map2 = new HashMap<>();
        map2.put("B", 3);
        map2.put("C", 4);
        map1.putAll(map2);
        //后者替代牵着
        System.out.println(map1); // {A=1, B=3, C=4}
    }

    @Test
    public void f() {
        Map<String, Integer> map1 = new HashMap<>();
        map1.put("A", 1);
        map1.put("B", 2);
        Map<String, Integer> map2 = new HashMap<>();
        map2.put("B", 3);
        map2.put("C", 4);
        map1.putAll(map2);

        map1.forEach((key, value) -> {
            map2.merge(key, value, (oldValue, newValue) -> oldValue);
        });
        System.out.println(map2);
    }
}
